package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vehiclemanagement.common.result.Result;
import com.vehiclemanagement.entity.ETCPassage;
import com.vehiclemanagement.service.ETCPassageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * ETC通行记录控制器
 */
@RestController
@RequestMapping("/api/etc-passage")
@Slf4j
public class ETCPassageController {

    @Autowired
    private ETCPassageService etcPassageService;

    /**
     * 分页查询ETC通行记录
     */
    @GetMapping("/list")
    public Result<IPage<ETCPassage>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String searchTerm,
            @RequestParam(required = false) Long vehicleId,
            @RequestParam(required = false) Long etcCardId,
            @RequestParam(required = false) Integer passageType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        IPage<ETCPassage> page = etcPassageService.pagePassages(
                current, size, searchTerm, vehicleId, etcCardId, passageType, status, startTime, endTime);
        
        return Result.success(page);
    }

    /**
     * 根据ID获取ETC通行记录详情
     */
    @GetMapping("/{id}")
    public Result<ETCPassage> getById(@PathVariable Long id) {
        ETCPassage passage = etcPassageService.getPassageById(id);
        if (passage == null) {
            return Result.error("找不到指定的ETC通行记录");
        }
        return Result.success(passage);
    }

    /**
     * 添加ETC通行记录
     */
    @PostMapping
    public Result<Boolean> add(@RequestBody ETCPassage passage) {
        // 校验必填字段
        if (passage.getVehicleId() == null) {
            return Result.error("车辆ID不能为空");
        }
        if (passage.getEtcCardId() == null) {
            return Result.error("ETC卡ID不能为空");
        }
        if (passage.getEntryStation() == null || passage.getEntryStation().trim().isEmpty()) {
            return Result.error("入口站点不能为空");
        }
        if (passage.getExitStation() == null || passage.getExitStation().trim().isEmpty()) {
            return Result.error("出口站点不能为空");
        }
        if (passage.getFee() == null) {
            return Result.error("通行费用不能为空");
        }
        
        boolean success = etcPassageService.addPassage(passage);
        return success ? Result.success(true) : Result.error("添加ETC通行记录失败");
    }

    /**
     * 更新ETC通行记录
     */
    @PutMapping
    public Result<Boolean> update(@RequestBody ETCPassage passage) {
        if (passage.getId() == null) {
            return Result.error("ETC通行记录ID不能为空");
        }
        
        boolean success = etcPassageService.updatePassage(passage);
        return success ? Result.success(true) : Result.error("更新ETC通行记录失败");
    }

    /**
     * 删除ETC通行记录
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        boolean success = etcPassageService.deletePassage(id);
        return success ? Result.success(true) : Result.error("删除ETC通行记录失败");
    }

    /**
     * 结算ETC通行记录
     */
    @PutMapping("/settle/{id}")
    public Result<Boolean> settle(@PathVariable Long id) {
        boolean success = etcPassageService.settlePassage(id);
        return success ? Result.success(true) : Result.error("结算ETC通行记录失败");
    }

    /**
     * 批量结算ETC通行记录
     */
    @PutMapping("/batch-settle")
    public Result<Integer> batchSettle(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要结算的ETC通行记录");
        }
        
        int count = etcPassageService.batchSettlePassages(ids);
        return count > 0 ? Result.success(count) : Result.error("批量结算ETC通行记录失败");
    }

    /**
     * 获取车辆的ETC通行总费用
     */
    @GetMapping("/sum-fee/vehicle/{vehicleId}")
    public Result<BigDecimal> sumFeeByVehicleId(@PathVariable Long vehicleId) {
        BigDecimal sum = etcPassageService.sumFeeByVehicleId(vehicleId);
        return Result.success(sum == null ? BigDecimal.ZERO : sum);
    }

    /**
     * 获取ETC卡的通行总费用
     */
    @GetMapping("/sum-fee/etc-card/{etcCardId}")
    public Result<BigDecimal> sumFeeByEtcCardId(@PathVariable Long etcCardId) {
        BigDecimal sum = etcPassageService.sumFeeByEtcCardId(etcCardId);
        return Result.success(sum == null ? BigDecimal.ZERO : sum);
    }

    /**
     * 按月统计ETC通行费用
     */
    @GetMapping("/statistics/month")
    public Result<List<Map<String, Object>>> statisticsByMonth(@RequestParam(required = false) Integer year) {
        List<Map<String, Object>> statistics = etcPassageService.statisticsByMonth(year);
        return Result.success(statistics);
    }

    /**
     * 按通行类型统计ETC通行费用
     */
    @GetMapping("/statistics/passage-type")
    public Result<List<Map<String, Object>>> statisticsByPassageType(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        List<Map<String, Object>> statistics = etcPassageService.statisticsByPassageType(startTime, endTime);
        return Result.success(statistics);
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("ETC通行记录API测试成功");
    }
} 